/*
* 设备巡检列表
* */

import 'package:center_beijing/api/task_api.dart';
import 'package:center_beijing/common/notification.dart';
import 'package:center_beijing/common/styles.dart';
import 'package:center_beijing/config/global_config.dart';
import 'package:center_beijing/config/routeConfig.dart';
import 'package:center_beijing/widgets/custom_loading_widget.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:get/get.dart';

class EquipmentInspection extends StatefulWidget {
  @override
  _EquipmentInspectionState createState() => _EquipmentInspectionState();
}

class _EquipmentInspectionState extends State<EquipmentInspection>
    with TickerProviderStateMixin {
  EasyRefreshController _controller = EasyRefreshController();
  CustomLoading loading = CustomLoading.withMessage('提交中...');
  var selectTask = Get.arguments;
  List dataSource = [];
  int page = 1;
  int pageSize = 15;
  bool firstLoad = true;

  @override
  void initState() {
    super.initState();
    this.getEquipmentTask();
    bus.on('refreshEquipList', (arg) {
      page = 1;
      this.getEquipmentTask();
    });
  }

  @override
  void dispose() {
    _controller.dispose();
    bus.off('refreshEquipList');
    loading.dismiss();
    super.dispose();
  }

  getEquipmentTask() async {
    var pass = {
      'planId': selectTask['id'],
      'page': page,
      'limit': pageSize,
    };
    var result = await getEquipmentOfTask(pass);
    if (this.page == 1) {
      dataSource.clear();
    }
    firstLoad = false;
    if (result != null) {
      if (result['results'].length == 0) {
        _controller.finishLoad(success: true);
      } else {
        dataSource.addAll(result['results']);
      }
    }
    this.setState(() {});
  }

  submit() async {
    var pass = {
      'planId': selectTask['id'],
    };
    loading.show(delay: 30);
    var result = await subPlanStatusById(pass);
    loading.dismiss();
    if (result['text'] != null && result['text'] == '') {
      bus.emit('refreshEquipmentTask');
      Fluttertoast.showToast(msg: '提交成功');
      Get.back();
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text('设备巡检'),
        ),
        body: Container(
          color: Styles.MainBackgroundColor,
          padding: EdgeInsets.fromLTRB(
              0, 0, 0, MediaQuery.of(context).padding.bottom + 70),
          child: NotificationListener(
            onNotification: (_) {
              FocusScope.of(context).requestFocus(new FocusNode());
              return false;
            },
            child: this.dataSource.length > 0
                ? EasyRefresh.custom(
                    shrinkWrap: true,
                    firstRefresh: false,
                    controller: _controller,
                    header: MaterialHeader(),
                    footer: ClassicalFooter(
                        loadingText: '加载中',
                        loadText: '上拉加载',
                        noMoreText: '没有更多数据',
                        loadedText: '加载完成',
                        infoText: '更新于 %T',
                        textColor: Styles.NoMoreColor,
                        showInfo: false),
                    emptyWidget: (dataSource.length == 0 && !firstLoad)
                        ? Center(
                            child: Image(
                              image: AssetImage('assets/images/no_data.png'),
                              width: 128,
                              height: 150,
                            ),
                          )
                        : null,
                    onLoad: () async {
                      await Future.delayed(Duration(seconds: 2), () {
                        if (mounted) {
                          page++;
                          this.getEquipmentTask();
                        }
                      });
                    },
                    onRefresh: () async {
                      _controller.finishLoad(success: true, noMore: false);
                      if (mounted) {
                        page = 1;
                        this.getEquipmentTask();
                      }
                    },
                    slivers: <Widget>[
                        SliverList(
                          delegate: SliverChildBuilderDelegate(
                            (context, index) {
                              return GestureDetector(
                                onTap: () {
                                  Get.toNamed(
                                      RouteConfig.equipmentInspectionDetail,
                                      arguments: {
                                        'equipment': this.dataSource[index],
                                        'planId': selectTask['id']
                                      });
                                },
                                child: Container(
                                  color: Colors.white,
                                  margin: EdgeInsets.fromLTRB(
                                      0, Styles.spacing8, 0, 0),
                                  padding: EdgeInsets.fromLTRB(
                                      Styles.spacing12,
                                      Styles.spacing8,
                                      Styles.spacing12,
                                      Styles.spacing8),
                                  child: Row(
                                    crossAxisAlignment:
                                        CrossAxisAlignment.center,
                                    children: [
                                      Expanded(
                                          child: Container(
                                        padding: EdgeInsets.fromLTRB(
                                            Styles.spacing12, 0, 0, 0),
                                        child: Column(
                                          crossAxisAlignment:
                                              CrossAxisAlignment.start,
                                          children: [
                                            Row(
                                              mainAxisAlignment:
                                                  MainAxisAlignment
                                                      .spaceBetween,
                                              crossAxisAlignment:
                                                  CrossAxisAlignment.start,
                                              children: [
                                                Expanded(
                                                  child: Container(
                                                    child: Text(
                                                      '设备编号:${this.dataSource[index]['code'] != null ? this.dataSource[index]['code'] : '--'}',
                                                      style: TextStyle(
                                                          color: Styles
                                                              .DetailColor,
                                                          fontSize: Styles
                                                              .NormalFont),
                                                    ),
                                                  ),
                                                ),
                                                Container(
                                                  margin: EdgeInsets.fromLTRB(0,
                                                      0, Styles.spacing16, 0),
                                                  child: Text(
                                                    this.dataSource[index][
                                                                'recordStatus'] ==
                                                            '1'
                                                        ? '已巡检'
                                                        : '未巡检',
                                                    style: TextStyle(
                                                        color: this.dataSource[
                                                                        index][
                                                                    'recordStatus'] ==
                                                                '1'
                                                            ? Styles
                                                                .tabGreenCard
                                                            : Styles.RedColor),
                                                  ),
                                                )
                                              ],
                                            ),
                                            Container(
                                              padding: EdgeInsets.fromLTRB(
                                                  0, Styles.spacing4, 0, 0),
                                              child: Text(
                                                '设备名称:${this.dataSource[index]['equipmentName'] != null ? this.dataSource[index]['equipmentName'] : '--'}',
                                                style: TextStyle(
                                                    color: Styles.DetailColor,
                                                    fontSize:
                                                        Styles.NormalFont),
                                              ),
                                            ),
                                            Container(
                                              padding: EdgeInsets.fromLTRB(
                                                  0, Styles.spacing4, 0, 0),
                                              child: Text(
                                                '设备位置:${this.dataSource[index]['address'] != null ? this.dataSource[index]['address'] : '--'}',
                                                style: TextStyle(
                                                    color: Styles.DetailColor,
                                                    fontSize:
                                                        Styles.NormalFont),
                                              ),
                                            ),
                                          ],
                                        ),
                                      )),
                                      GestureDetector(
                                        onTap: () {
                                          Get.toNamed(
                                              RouteConfig
                                                  .addEquipmentInspection,
                                              arguments: {
                                                'equipment':
                                                    this.dataSource[index],
                                                'planId': selectTask['id']
                                              });
                                        },
                                        child: Container(
                                          decoration: BoxDecoration(
                                              color: Styles.BlueColor,
                                              borderRadius: BorderRadius.all(
                                                  Radius.circular(4.0.r))),
                                          padding: EdgeInsets.fromLTRB(
                                              Styles.spacing8,
                                              Styles.spacing4,
                                              Styles.spacing8,
                                              Styles.spacing4),
                                          child: Text(
                                            '巡检',
                                            style: TextStyle(
                                                color: Styles.ShareWhite,
                                                fontSize: Styles.NormalFont),
                                          ),
                                        ),
                                      )
                                    ],
                                  ),
                                ),
                              );
                            },
                            childCount: dataSource.length,
                          ),
                        ),
                      ])
                : firstLoad
                    ? Center(
                        child: CircularProgressIndicator(),
                      )
                    : Center(
                        child: Image(
                          image: AssetImage('assets/images/no_data.png'),
                          width: 128,
                          height: 150,
                        ),
                      ),
          ),
        ),
        floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked,
        floatingActionButton: dataSource.length > 0
            ? Container(
                padding: EdgeInsets.fromLTRB(
                    Styles.spacing8, Styles.spacing8, Styles.spacing8, 10),
                child: Container(
                  decoration: new BoxDecoration(
                    //背景
                    color: Styles.BlueColor,
                    //设置四周圆角 角度
                    borderRadius: BorderRadius.all(Radius.circular(12.0)),
                  ),
                  child: FlatButton(
                    disabledColor: Styles.SelectColor,
                    onPressed: () {
                      FocusScope.of(context).requestFocus(new FocusNode());
                      showDialog(
                          barrierDismissible: false,
                          context: this.context,
                          builder: (BuildContext context) {
                            return AlertDialog(
                              title: Text('注意'),
                              content: Text('确认提交吗？'),
                              actions: <Widget>[
                                new Container(
                                  child: FlatButton(
                                    child: new Text(
                                      "取消",
                                      style: TextStyle(color: Colors.black),
                                    ),
                                    onPressed: () {
                                      Navigator.pop(context);
                                    },
                                  ),
                                ),
                                new Container(
                                  child: FlatButton(
                                    child: new Text(
                                      "确定",
                                      style: TextStyle(color: Colors.red),
                                    ),
                                    onPressed: () {
                                      Navigator.pop(context);
                                      this.submit();
                                    },
                                  ),
                                ),
                              ],
                            );
                          });
                    },
                    child: Container(
                      height: Styles.MainButtonHeight,
                      alignment: Alignment.center,
                      child: Text(
                        '提交巡检',
                        style: TextStyle(
                            fontSize: Styles.MainButtonTextFont,
                            color: Colors.white),
                      ),
                    ),
                  ),
                ),
              )
            : Container());
  }
}
